package com.itheima.aspect;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author wuJiaWei
 * @version 1.0
 */
@Slf4j
@Aspect //标识当前类是一个切面类
@Component //交给springIOC容器管理
public class CurdLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;//注入请求对象


    @Pointcut("@annotation(com.itheima.anno.CurdLog)")
    public void pointCut(){}

    @Around("pointCut()")
    public Object recordCurdLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //操作人ID - 当前登录员工ID
        // 获取请求头中的jwt令牌，解析令牌
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer operateUser = (Integer) claims.get("id");

        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //操作类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodName = proceedingJoinPoint.getSignature().getName();

        //操作方法参数
        String methodParams = Arrays.toString(proceedingJoinPoint.getArgs());

        // 记录开始时间
        long startTime = System.currentTimeMillis();
        // 调用原始方法运行
        Object result = proceedingJoinPoint.proceed();
        // 记录结束时间
        long endTime = System.currentTimeMillis();

        //方法返回值
        String returnValue = JSONObject.toJSONString(result);

        // 操作耗时
        Long costTime = endTime - startTime;

        // 封装操作日志对象
        OperateLog build = OperateLog.builder()
                .operateUser(operateUser)
                .operateTime(operateTime)
                .className(className)
                .methodName(methodName)
                .methodParams(methodParams)
                .returnValue(returnValue)
                .costTime(costTime)
                .build();
        operateLogMapper.insert(build);
        // 打印方法执行耗时
        log.info(className+methodName+"耗时：{}", endTime - startTime);
        // 把目标方法的执行结果返回
        return result;
    }

}
